<template>
  <div>
    <Panel :title="title">
      <div class slot="ext">
        <slot name="button" />
      </div>
      <div slot="body">
        <TableEncapsulation
          :changeSelectRow="(ids) => multipleSelection = ids"
          :tableConfig="tableConfig"
          :tableData="tableData"
        >
          <template slot="operation" slot-scope="operation">
            <el-button type="text" @click="()=>modifyRow(operation.row, operation.index)">编辑</el-button>
          </template>
        </TableEncapsulation>
      </div>
    </Panel>
    <ModalPanel
      :class="$style.basePageModal"
      :destroy-on-close="true"
      v-on="$listeners"
      :title="modalTitle"
      :modal="false"
      :visible="visible"
      :onCancel="onCancel"
      :onOk="onSubmit"
    >
      <el-form
        size="medium"
        label-width="80px"
        :model="temporaryData"
        ref="formdoalog"
        :rules="formdialog"
        :validate-on-rule-change="false"
      >
        <el-row>
          <el-col :span="item.width || 12" v-for="item of editColumn" :key="item.prop">
            <el-form-item :label="item.name" :prop="item.prop">
              <template v-if="item.type==='text'">
                <el-input :placeholder="'请输入'+item.name" v-model="temporaryData[item.prop]"></el-input>
              </template>
              <template v-else-if="item.type==='number'">
                <el-input
                  type="number"
                  :placeholder="'请输入'+item.name"
                  v-model="temporaryData[item.prop]"
                ></el-input>
              </template>
              <template v-else-if="item.type==='time'">
                <el-date-picker
                  v-model="temporaryData[item.prop]"
                  type="date"
                  value-format="timestamp"
                  :placeholder="'请输入'+item.name"
                ></el-date-picker>
              </template>
              <template v-else-if="item.type==='inputNumber'">
                <el-input-number
                  v-model="temporaryData[item.prop]"
                  @change="value => $attrs[item.prop]?$attrs[item.prop](value):{}"
                  :min="1"
                ></el-input-number>
              </template>
              <template v-else-if="item.type==='textarea'">
                <el-input
                  v-model="temporaryData[item.prop]"
                  :placeholder="'请输入'+item.name"
                  type="textarea"
                ></el-input>
              </template>

              <template v-else-if='item.type === "password"'>
                <el-input type="password"
                  v-model="temporaryData[item.prop]"
                  placeholder='请输入密码'></el-input>
              </template>
              <template v-else-if="item.type==='other'" class="111">
                <slot :name="item.slotName" :data="temporaryData[item.prop]" :item="item" class="eeeee" />
              </template>

              <template v-else-if="item.type==='select'">
                <el-select
                  v-model="temporaryData[item.prop]"
                  @change="value => $attrs[item.prop] ? $attrs[item.prop](value) : {}"
                  :placeholder="'请输入'+item.name"
                >
                  <el-option
                    v-for="(optionItem,index) of item.optionList"
                    :key="optionItem.id || index"
                    :label="item.optionBindLabel ? optionItem[item.optionBindLabel] : optionItem.name"
                    :value="item.optionBindValue ? optionItem[item.optionBindValue] : optionItem.value"
                  ></el-option>
                </el-select>
              </template>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </ModalPanel>
  </div>
</template>
<script>
import Panel from "@/components/Panel";
import ModalPanel from "@/components/ModalPanel";
import TableEncapsulation from "@/components/treeTable";
import TablePager from "@/components/Pager";
import { arrayToObject } from "@/tools/array";
export default {
  components: {
    Panel,
    TableEncapsulation,
    ModalPanel,
    TablePager
  },
  props: {
    title: {
      type: String,
      default: ""
    },
    parentId:{
      type: String,
      default: ""
    },
    tableData: {
      type: Array,
      default: () => []
    },
    tableConfig: {
      type: Object,
      default: () => ({})
    },
    editColumn: {
      type: Array,
      default: () => []
    },
    updateData: {
      type: Function,
      default: () => {}
    },
    urlList: {
      type: Object,
      default: () => ({})
    },
    pager: {
      type: Object,
      default: () => ({})
    },
    openModal: {
      // 打开弹框时，回调这个函数
      type: Function,
      default: () => {}
    }
  },
  data() {
    return {
      modalTitle: "",
      visible: false,
      isCreate: false,
      temporaryData: {},
      multipleSelection: []
    };
  },
  computed: {
    formdialog() {
      let arr = this.editColumn
        .filter(item => item.required)
        .map(item => ({
          [item.prop]: {
            required: true,
            message: item.name + "不能为空",
            trigger: "blur"
          }
        }));
      return arrayToObject(arr, "prop");
    },
  },
  methods: {
    // 包装对外函数
    packagingFunction (fnc) {
      return () => fnc([...this.multipleSelection], {...this.temporaryData})
    },
    onCancel() {
      this.temporaryData = {};
      this.visible = false;
      this.$refs["formdoalog"].resetFields();
    },
    createRow() {
      let getDefaultList = this.editColumn
        .filter(item => item.default)
        .map(item => ({ [item.prop]: item.default }));
      this.temporaryData = { ...arrayToObject(getDefaultList) };
      this.openModal("create", { ...this.temporaryData });
      this.modalTitle = "新建" + this.title;
      this.isCreate = true;
      this.visible = true;
    },
    modifyRow(rowData, index) {
      this.openModal("edit", { ...rowData });
      this.modalTitle = "编辑" + this.title;
      this.isCreate = false;
      this.temporaryData = { ...rowData };
      try{
        this.$attrs.modifyFunc()
      } catch(err){
      }
      this.visible = true;
    },
    async deleteRow() {
      if (this.multipleSelection.length === 0) {
        this.$message({
          message: "请先选择要删除的项",
          type: "warning"
        })
      } else {
        await this.$store.dispatch({
          type: "sysSetting/delete",
          ids: this.multipleSelection,
          url: this.urlList.deleteUrl
        });
        this.multipleSelection = [];
        this.updateData('update');
        this.onCancel();
      }
    },

    async onSubmit() {
      let parentIds
      if(!this.parentId) {
        parentIds = 0
      }else{
        let count = this.parentId.length - 1
         parentIds = this.parentId[count]
      }
      // console.log('保存数据',{ ...this.temporaryData,'parentId':parentIds })
      // return
      this.$refs["formdoalog"].validate(async valid => {
        if (valid) {
          if (this.isCreate) {
            await this.$store.dispatch({
              type: "sysSetting/create1",
              values: { ...this.temporaryData,'parentId':parentIds },
              url: this.urlList.createUrl
            });
          } else {
            await this.$store.dispatch({
              type: "sysSetting/create1",
              values:{ ...this.temporaryData,'parentId':parentIds },
              url: this.urlList.modifyUrl
            });
          }
          this.updateData('update');
          this.onCancel();
        } else {
          return false;
        }
      });
    },
    pageChange(val) {
      this.updateData('update', { current: val });
    }
  },
  mounted() {},
  created() {}
};
</script>
<style lang='scss' module>
.basePageModal {
  :global {
    .el-dialog__body {
      padding-bottom: 0;
    }
    .el-input-number--medium {
      width: 220px;
    }
  }
}
</style>

